import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Card, message, Spin, Alert, Result } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { loginStudent, clearError } from '../../store/slices/authSlice';
import './index.scss';

const Login = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const { loading, error, isAuthenticated, token, user } = useSelector((state) => state.auth);
  const [loginSuccess, setLoginSuccess] = useState(false);
  
  // 获取重定向的来源路径
  const from = location.state?.from?.pathname || '/dashboard';

  useEffect(() => {
    // 如果已经登录，重定向到来源页面或首页
    if (isAuthenticated && !loginSuccess) {
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, navigate, from, loginSuccess]);

  useEffect(() => {
    // 处理错误信息
    if (error) {
      message.error(error);
      dispatch(clearError());
    }
  }, [error, dispatch]);

  const onFinish = async (values) => {
    try {
      const response = await dispatch(loginStudent({
        studentId: values.studentId,
        password: values.password,
      })).unwrap();
      
      // 从响应中提取token和student
      let token, student;
      
      // 根据截图中的响应格式处理
      if (response && response.code === 2000) {
        // 直接从响应中获取token
        token = response.token;
        student = response.student;
      } else if (response && response.data) {
        // 从嵌套的data中获取token
        token = response.data.token;
        student = response.data.student;
      } else if (response) {
        // 可能是直接返回的token和student
        token = response.token;
        student = response.student;
      }
      
      // 检查token是否已经存储到localStorage
      let storedToken = localStorage.getItem('token');
      if (!storedToken) {
        // 如果localStorage中没有token，但我们从响应中提取到了token，则存储它
        if (token) {
          localStorage.setItem('token', token);
          storedToken = token;
          
          if (student) {
            localStorage.setItem('user', JSON.stringify(student));
          }
        }
      }
      
      // 最终检查token是否存储成功
      if (storedToken) {
        setLoginSuccess(true);
        
        // 显示成功提示，1.5秒后跳转
        setTimeout(() => {
          navigate(from, { replace: true });
        }, 1500);
      } else {
        message.error('登录失败：未能获取或存储授权令牌');
      }
    } catch (err) {
      message.error(err?.message || '登录失败，请稍后重试');
    }
  };

  // 如果登录成功，显示成功结果页面
  if (loginSuccess) {
    return (
      <div className="login-container">
        <Card className="login-card">
          <Result
            status="success"
            title="登录成功！"
            subTitle="正在跳转到系统首页..."
          />
        </Card>
      </div>
    );
  }

  return (
    <div className="login-container">
      <Card className="login-card" title="学生登录">
        <Spin spinning={loading}>
          {error && (
            <Alert
              message="登录失败"
              description={error}
              type="error"
              showIcon
              closable
              style={{ marginBottom: 24 }}
              onClose={() => dispatch(clearError())}
            />
          )}
          
          <Form
            form={form}
            name="login"
            onFinish={onFinish}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="studentId"
              rules={[
                {
                  required: true,
                  message: '请输入学号！',
                },
              ]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="学号"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                className="login-button"
                loading={loading}
                block
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          
          <div className="login-footer">
            <Link to="/register">没有账号？立即注册</Link>
          </div>
        </Spin>
      </Card>
    </div>
  );
};

export default Login;